package com.qipay.sms.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.qipay.sms.config.AliyunSMSCodeEnum;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Creator: Yao
 * Date:    2017/10/18
 * For:
 * Other:
 */
@Component
public class ALliyunSMSUtils {

    final static Logger logger = LogManager.getLogger(ALliyunSMSUtils.class);
    final static Gson gson = new Gson();

    @Value("${aliyun.sms.product:}")
    private String product;
    @Value("${aliyun.sms.domain:}")
    private String domain;
    @Value("${aliyun.sms.timeout.connect:}")
    private String defaultConnectTimeout;
    @Value("${aliyun.sms.timeout.read:}")
    private String defaultReadTimeout;

    @Value("${aliyun.sms.access.key.id:}")
    private String accessKeyId;
    @Value("${aliyun.sms.access.key.secret:}")
    private String accessKeySecret;
    @Value("${aliyun.sms.sign:}")
    private String sign;

    /***
     * 单条短信发送 - 推荐
     * @param phone     手机号
     * @param template  短信模板
     * @param info      模板所需填充参数值
     * @return
     */
    public String send(String phone, String template, String info) {

        // log
        logger.info(String.format("send(%s, %s, %s)", phone, template, info));

        // init.system
        System.setProperty("sun.net.client.defaultConnectTimeout", defaultConnectTimeout);
        System.setProperty("sun.net.client.defaultReadTimeout", defaultReadTimeout);

        // init.request
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(sign);
        request.setTemplateCode(template);
        request.setTemplateParam(info);

        // init.response
        String response = AliyunSMSCodeEnum.ERROR.getInfo();

        try {

            // init
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            // send
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            response = AliyunSMSCodeEnum.convert(sendSmsResponse.getCode());

            // log
            logger.info("sms.send.response= " + gson.toJson(sendSmsResponse));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return response;
    }
}
